package carson.web.mvc;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * 将文件流发送到响应
 *
 * @author Carson Chen
 */
public class FileStreamResult extends AbstractFileResult {

    /**
     * 实例化FileStreamResult
     *
     * @param fileStream       文件流
     * @param contentType      内容类型
     * @param fileDownloadName 下载时的文件名
     */
    public FileStreamResult(InputStream fileStream, String contentType, String fileDownloadName) {
        super(contentType);
        this.fileStream = fileStream;
        setFileDownloadName(fileDownloadName);
    }

    private InputStream fileStream;

    /**
     * 获取文件流
     *
     * @return 文件流
     */
    public InputStream getFileStream() {
        return fileStream;
    }

    @Override
    protected void writeFile(HttpServletResponse response) throws IOException {
        int status = 0;
        byte[] b = new byte[1024];
        InputStream in = null;
        ServletOutputStream out2 = null;
        try {
            response.setHeader("content-disposition", "attachment; filename="
                    + java.net.URLEncoder.encode(getFileDownloadName(), "UTF-8"));
            in = this.fileStream;
            out2 = response.getOutputStream();
            while (status != -1) {
                status = in.read(b);
                out2.write(b);
            }
            out2.flush();
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            if (in != null)
                in.close();
            if (out2 != null)
                out2.close();
        }
    }
}
